using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Xml;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ACM.cmsarea08;
using ACM.cmsarea08.Controls;
using ACM.cmsarea08.Administration;



namespace ACM.cmsarea08.Administration.Core {
	public partial class EditBloccoV :  BaseEditPage {
		//protected itareanet.cmsarea08.Administration.Controls.MainButton adm_buttons;
		
		
		override protected void OnInit(EventArgs e)
		{
			if(ACM.cmsarea08.Users.CurrentUser.Role.Score>400)
				Response.Redirect("/loginadm.aspx?returnurl="+
								HttpUtility.UrlEncode(Request.ServerVariables["SCRIPT_NAME"].ToString()+
				                                        (Request.ServerVariables["QUERY_STRING"].ToString()==""?"":"?"+Request.ServerVariables["QUERY_STRING"].ToString()))
	);
			else if(ACM.cmsarea08.Users.CurrentUser.Role.Score>100)
				Response.Redirect("/administration/accessdeny.aspx");
			base.OnInit(e);
			InitializeComponent();
			
			
			
		}
		const string DBActionTable = "blocco_visivo";
		private string _ItemID;
		public bool InsertMode {
			get {
				if(Request.QueryString["new"]==null)
					return false;
				else if( Request.QueryString["new"].ToString()=="1")
					return true;
				else
					return false;
			}
		}
//		public string ItemID {
//				get { return _ItemID;				}
//				set { _ItemID = value; }
//			}
		
		protected DBClass dclass = new DBClass();
		private void InitializeComponent()
		{
//			if(this.Master is itareanet.cmsarea08.Administration.Core.ListerPrivate) {
//
//			}
			_ItemID = Request.QueryString["idf"]!=null?Request.QueryString["idf"].ToString():"0";
			if(adm_buttons!=null) {
				adm_buttons.StandardForm = false;
				NonStandardForm nsfOggettoForm = new NonStandardForm();
				nsfOggettoForm.Titolo = (this.InsertMode?
				                         rm.GetString("new_viewsblockH"):
				                         rm.GetString("upd_viewsblockH"));
				nsfOggettoForm.FormName = "edit_blocco_visivo";
				nsfOggettoForm.XmlPath = "/administration/edit_form/edit_blocco_visivo";
				//opzionale:
				nsfOggettoForm.XslPath = "";
				/* questo blocco va impostato solo se siamo in MODIFICA, previa query a DB */
				nsfOggettoForm.DbTable = DBActionTable; // un sieabbi a nianti
				nsfOggettoForm.KeyField = "id"; // un sieabbi a nianti
				//pezzo lettura params da db - se update
				nsfOggettoForm.FormData = null;
				string datains = "-";
				string datamod = "-";
				string footer = rm.GetString("data_ins") + ": <b>{0}</b> | " + rm.GetString("data_mod") + ": <b>{1}</b>";
				
				if(!InsertMode){
					DataSet ds = dclass.Helper_Dataset("select id, titolo, data_mod, data_ins from " +
					                                   ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + DBActionTable + 
					                                   " where id='" + _ItemID +"' limit 1 ;");
//					Response.Write("select id, titolo, data_mod, data_ins from " +
//					                                   itareanet.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + DBActionTable + 
//					                                   " where id='" + _ItemID +"' limit 1 ;");
					if(ds!=null){
						datains = ds.Tables[0].Rows[0]["data_ins"].ToString();
						datamod = ds.Tables[0].Rows[0]["data_mod"].ToString();
					}
					
					
					_ItemID = Request.QueryString["idf"]!=null?Request.QueryString["idf"].ToString():"0";
					FormDataAdapter fda = new FormDataAdapter();
					
					//Response.Write(ds==null?"nullo":fda.DataSetToItanData(ds));
					
					nsfOggettoForm.FormData = ds!=null?fda.DataSetToItanData(ds):null;
				}
				
				nsfOggettoForm.Footer = string.Format(footer,datains,datamod);
					
					
				
				/* fine blocchetto, casomai mettere in questo blocco le stringhe a "" e l'obj a null  */
				
				
				
				
				//Assegnazione delle Cose alla pulsanteria:
				adm_buttons.SaveFormClicked += new SaveFormEventHandler(EVENTOSALVA);
				
				adm_buttons.NSFormData = nsfOggettoForm;
			}
			//adm_buttons.CaricaLayoutForm();
			this.Load += new System.EventHandler(this.Page_Load);
			
		}
	
		private void Page_Load(object o , EventArgs e) {
			_ItemID = Request.QueryString["idf"]!=null?Request.QueryString["idf"].ToString():"0";
			if(!Page.IsPostBack) {
				
			}
		}
		public void EVENTOSALVA(object o, SaveFormEventArgs e) {
			//devo salvare.
			// e.FormData
			// e.CommandType
			string query = "";
			if(e.CommandType==ACM.cmsarea08.CommandTypes.Insert)
				query = "insert into {0} (titolo, data_mod, data_ins) values ('{1}',Now(),Now()) ;";
			else if(e.CommandType==ACM.cmsarea08.CommandTypes.Update){
				if(_ItemID == "0"){
					this.PrintMessage(rm.GetString("error_querystring"));
					return;
				}
				query = "update {0} set titolo='{1}', data_mod=Now() where id='"+ _ItemID +"' limit 1 ;";
			}
			//Response.Write("DOVREI FARE QUALCOSA: " + e.CommandType + "<br>");
			XmlDocument xdoc = new XmlDocument();
			if(e.FormData!=null) {
				FormDataAdapter fda = new FormDataAdapter();
				xdoc = fda.ObjectToXmlDocument(e.FormData);
				if(xdoc==null) {
					//Response.Write("no data");
					return;
			}
				XmlNode node;
				node = xdoc.DocumentElement;
				string nodoTitolo="";
				if (node.SelectSingleNode("//impostazioni/set[nome=\"titolo\"]").ChildNodes.Count>=2)
					nodoTitolo = node.SelectSingleNode("//impostazioni/set[nome=\"titolo\"]").ChildNodes[1].InnerText;
				
				
				ACM.cmsarea08.Function.TextClass tclass = new ACM.cmsarea08.Function.TextClass();
				object obj=null;
				if(nodoTitolo.Trim()!="")
					obj = dclass.HStandard_SC("select count(*) from "+ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle+DBActionTable+" where titolo='"+tclass.SqlTesto(nodoTitolo)+"';");
				
				if(obj!=null && obj.ToString()=="0"){
				query = string.Format(query,ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + DBActionTable,
				                      tclass.SqlTesto(nodoTitolo));
				//Response.Write("XML: <hr>" + HttpUtility.HtmlEncode(xdoc.InnerXml) + "<hr>Ho eseguito: " + query + "<hr>");
				int reso = 0;
				try{
					reso = dclass.ExecuteScalar(query);
				
					if(reso<1)
						this.PrintMessage(rm.GetString("error_db"));
					else{
						if(InsertMode)
							this.PrintMessage(rm.GetString("success_ins_vblock"));
						else
							this.PrintMessage(rm.GetString("success_upd_vblock"));
					}
					
				}
				catch(MySql.Data.MySqlClient.MySqlException ex){
					this.PrintMessage(rm.GetString("error_db"));
					Response.Write(ex.ToString());
				}
				}else{
					if(nodoTitolo.Trim()=="")
						this.PrintMessage(rm.GetString("error_invalid_data"));
					else
					this.PrintMessage(rm.GetString("error_same_name"));
				}
			
			}
			//this.PrintMessage("formdata null");
			
			
			//quando devi stampare qualcosa:
			//this.PrintMessage("MESSAGGIO");
		}
		
		
	}
	
}
